import { Icon, Row, Button, Input } from "antd";
import { Grid, ListView, Tabs, Toast, WhiteSpace } from "antd-mobile";
import { addon } from "pao-aop";
import { reactControl, ReactView, ReactViewControl, ReactViewState } from "pao-aop-client";
import React from "react";
import { AppServiceUtility } from "src/projects/app/appService";
import { forceCheckIsLogin, ROUTE_PATH } from "src/projects/app/util-tool";
import { remote } from "src/projects/remote";
import { LoadingEffectView } from "src/business/views/loading-effect";

function MyBody(props: any) {
    return (
        <div className="am-list-body my-body" style={{ height: '100%' }}>
            {props.children}
        </div>
    );
}
/**
 * 组件：老友圈视图状态
 */
export interface FriendCircleViewState extends ReactViewState {
    // 数据
    data?: any;
    /** 长列表数据 */
    dataSource?: any;
    /** 长列表容器高度 */
    height?: any;
    /** 评论的数据 */
    commont_list?: any;
    // 评论输入框
    commont_input?: boolean;
    /** 评论的内容 */
    commont?: string;
    notice?: string;
    upload?: boolean;
}

/**
 * 组件：老友圈视图
 * 老友圈视图
 */
export class FriendCircleView extends ReactView<FriendCircleViewControl, FriendCircleViewState> {
    input: Input;
    constructor(props: any) {
        super(props);
        const ds = new ListView.DataSource({
            rowHasChanged: (r1: any, r2: any) => r1 !== r2
        });
        this.state = {
            dataSource: ds,
            data: [],
            height: document.documentElement!.clientHeight,
            commont_list: {},
            commont_input: false,
            commont: '',
            notice: '正在加载',
            upload: true,
        };
    }
    componentDidMount() {
        AppServiceUtility.friends_circle.get_friends_circle_list!({})!
            .then((data: any) => {
                this.setState({ upload: false });
                if (data) {
                    if (data.result.length === 0) {
                        this.setState({
                            notice: '暂无数据',
                        });
                    }
                    this.setState({
                        data: data.result
                    });
                }
            })
            .catch((err) => {
                console.info(err);
                this.setState({ upload: false });
            });
    }
    publish = () => {
        forceCheckIsLogin(this.props, { successPath: ROUTE_PATH.publishFriendCircle }, { backPath: ROUTE_PATH.friendCircle });
        // this.props.history!.push(ROUTE_PATH.publishFriendCircle);
    }
    onLike = (id: string) => {
        AppServiceUtility.friends_circle.update_like!(id, '1')!
            .then((data: any) => {
                if (data === 'Success') {
                    Toast.info('点赞成功');
                    location.reload();
                }
            })
            .catch((err) => {
                console.info(err);
            });
    }
    onComment = (data: any) => {
        this.setState({
            commont_input: true,
            commont_list: data,
        });
        setTimeout(
            () => {
                this.input.focus();
            },
            0
        );
    }
    inputBlur = (e: any) => {
        console.info(e.target.nodeName);
        if (e.target.nodeName === 'DIV') {
            // do something
            this.setState({
                commont_input: false,
            });
        }

    }
    sub = () => {
        let fcm_id = this.state.commont_list.id;
        let commont = this.state.commont;
        if (!commont) {
            Toast.info('请输入评论内容');
            return;
        }
        AppServiceUtility.friends_circle.update_commont!(fcm_id, commont)!
            .then((data: any) => {
                if (data) {
                    if (data === 'Success') {
                        Toast.info('评论成功');
                        location.reload();
                    }
                }
            })
            .catch((err) => {
                console.info(err);
            });

    }
    commontChage = (value: any) => {
        value.persist();
        this.setState({
            commont: value.target.value,
        });
    }
    getNow(date: any) {
        if (!date) {
            return '';
        }
        date = date.substring(0, 19);
        // 必须把日期'-'转为'/'
        date = date.replace(/-/g, '/');
        let timestamp = new Date(date).getTime();
        let timestamps = new Date().getTime();
        let day = Math.floor(Math.abs(timestamps - timestamp) / (24 * 3600 * 1000));
        if (day <= 0) {
            return Math.floor(Math.abs(timestamps - timestamp) / (3600 * 1000)) + '小时前';
        } else {
            return date.split(' ')[0] + ' ' + Math.floor(Math.abs(timestamps - timestamp) / (24 * 3600 * 1000)) + '天前';
        }

    }
    render() {
        let { data, dataSource, } = this.state;
        const tabs = [
            { title: '广场', sub: '1' },
            { title: '我的圈子', sub: '2' },
        ];
        // 获取服务器地址
        let fileUrl = remote.upload_url.split('/')[0];
        // 获取item进行展示
        const renderRow = (owData: any, sectionID: any, rowID: any) => {
            let pct_list: any[] = [];
            if (owData.picture.length > 0) {
                owData.picture.map((value: any) => {
                    pct_list.push({ url: fileUrl + value });
                });
            }
            return (
                <div>
                    <div style={{ display: 'flex', padding: '15px 15px', borderBottom: '1px solid #ddd' }}>
                        <div style={{ height: '64px', }}>
                            <img style={{ height: '64px', width: '64px', borderRadius: '50%', marginRight: "15px" }} src={owData.user_picture && owData.user_picture.length > 0 ? owData.user_picture[0] : ''} alt="" />
                        </div>

                        <div style={{ width: '100%' }}>
                            <div style={{ marginBottom: '8px', fontWeight: 'bold' }}>{owData.name}</div>
                            <div>{owData.content}</div>
                            <div>
                                <Grid
                                    data={pct_list}
                                    columnNum={3}
                                    activeStyle={false}
                                    renderItem={dataItem => (
                                        <div>
                                            <img src={dataItem!.url} style={{ width: '75px', height: '75px' }} alt="" />
                                        </div>
                                    )}
                                />
                            </div>
                            <WhiteSpace size="sm" />
                            <Row>
                                {/* <Col span={12}>{owData && owData.create_date.split(' ').length > 0 ? owData.create_date.format("YYYY-MM-DD hh:mm") : ''}</Col> */}
                                <span style={{ fontSize: '12px' }}>{this.getNow(owData.create_date)}</span>
                                <span style={{ float: 'right', textAlign: 'right' }}>
                                    <span style={{ marginRight: '10px' }}>
                                        <Icon onClick={this.onLike.bind(this, owData.id)} style={{ marginRight: '5px' }} type="like" /><span style={{ marginRight: '5px' }}>赞</span>{owData.like_list.length}
                                    </span>
                                    <span style={{ marginRight: '10px' }}>
                                        <Icon onClick={this.onComment.bind(this, owData)} style={{ marginRight: '5px' }} type="message" /><span style={{ marginRight: '5px' }}>评论</span>{owData.comment.length}
                                    </span>
                                </span>
                            </Row>
                            <WhiteSpace size="sm" />
                            {
                                owData.comment && owData.comment.length > 0 ?
                                    <div
                                        style={{
                                            position: 'relative',
                                            background: '#d3d7d4',
                                            padding: '10px',
                                        }}
                                    >
                                        <span
                                            style={{
                                                position: 'absolute',
                                                top: '-16px',
                                                left: '16px'
                                            }}
                                        >
                                            <Icon style={{ color: '#d3d7d4', fontSize: '26px', }} type="caret-up" />
                                        </span>
                                        {
                                            owData.comment && owData.comment.length > 0 ?
                                                owData.comment.map((value: any, index: number) => {
                                                    return (
                                                        <div key={index}>
                                                            {value.content}
                                                        </div>
                                                    );
                                                }) : ""
                                        }
                                    </div> : ''
                            }

                        </div>
                    </div>

                </div>
            );
        };
        return (
            <div onClick={this.inputBlur} style={{ paddingBottom: '50px' }}>
                <Tabs
                    tabs={tabs}
                    initialPage={0}
                >
                    <div>
                        {this.state.upload && <LoadingEffectView />}
                        {
                            data && data.length ?
                                <ListView
                                    ref={el => this['lv'] = el}
                                    dataSource={dataSource.cloneWithRows(data)}
                                    renderRow={renderRow}
                                    initialListSize={10}
                                    pageSize={10}
                                    renderBodyComponent={() => <MyBody />}
                                    style={{ height: this.state.height }}
                                />
                                :
                                <Row className='tabs-content' type='flex' justify='center'>
                                    {this.state.notice}
                                </Row>

                        }

                    </div>
                    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', }}>
                        暂无数据
                </div>
                </Tabs>
                <div
                    onClick={this.publish}
                    style={{
                        position: 'fixed',
                        bottom: '150px',
                        right: '10px',
                        width: '50px',
                        height: '50px',
                        borderRadius: '50%',
                        textAlign: 'center',
                        zIndex: 9999,
                        background: '#fff',
                        lineHeight: '50px',

                    }}
                >
                    <Icon type="edit" style={{ fontSize: '20px' }} />
                </div>
                <div
                    style={{
                        position: 'fixed',
                        bottom: '0',
                        zIndex: 999,
                        height: '50px',
                        width: '100%',
                        background: '#ffffff',
                        display: this.state.commont_input ? 'block' : 'none',
                    }}
                >
                    <div
                        style={{
                            position: 'absolute',
                            height: '50px',
                            left: '0px',
                            right: '80px',
                            paddingLeft: '10px',
                        }}
                    >
                        <Input onChange={this.commontChage} ref={ref => this.input = ref!} style={{ width: '100%' }} />
                    </div>
                    <Button type='primary' onClick={this.sub} style={{ float: 'right', marginRight: "10px" }}>发送</Button>
                </div>
            </div>
        );
    }
}

/**
 * 控件：老友圈视图控制器
 * 老友圈视图
 */
@addon('FriendCircleView', '老友圈视图', '老友圈视图')
@reactControl(FriendCircleView, true)
export class FriendCircleViewControl extends ReactViewControl {
    constructor() {
        super();
    }
}